package com.health.viewscontrols.medical.device.comp;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.health.httpbean.model.BpModel;
import com.health.httpbean.model.FmModel;
import com.health.httpbean.model.WaistBean;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.SBCL_DATA;
import com.health.tablebean.SBCL_DATA_NEW;
import com.health.tools.GlobalConts;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.NovaGlobalConts;
import com.nova.health.ble.HexUtil;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.BlueToothConstant;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * 腰臀比
 */
public class DhCompositionActivity extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE =
            UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_NOTIFY =
            UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_WRITE =
            UUID.fromString("0000ffe2-0000-1000-8000-00805f9b34fb");
    private StringBuilder stringBuilderAscii = new StringBuilder();
    FmModel fmModelHeight;

    //    private String commStr = "#FM17550653032$";
    private String commStr = "#FM";
    // 是否测量身高体重
    private boolean isHeightAndWeightDataExit = false;
    protected String strWhere;

    Timer timer;
    TimerTask task;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            connDevice();
        }
    };

    @Override
    public void doBusiness() {

        if (!TextUtils.isEmpty(NovaApplication.getUserInfo().getIDCARD())) {
            strWhere = "IDCARD = '" + NovaApplication.getUserInfo().getIDCARD() + "'";
        } else {
            strWhere = "IDCARD = '" + NovaApplication.getUserInfo().getPHONE() + "'";
        }

        queryData();
        stringBuilderAscii.delete(0, stringBuilderAscii.length());

        tv_operation_tips.setText(com.nova.health.ble.R.string.rtgc_dh);
        mBleDevice.setDevice_Service_UUID(UUID_SERVICE);
        mBleDevice.setDevice_Notify_UUID(UUID_NOTIFY);
        mBleDevice.setDEVICE_write_UUID(UUID_WRITE);
        mBleDevice.setConnectChangedListener(new OnDeviceConnectChangedListener() {
            @Override
            public void onConnected() {
                Log.e(TAG, "onConnected: ");
                isConnected = true;
                runOnUiThread(() -> {
                    blueToothState.setText("蓝牙已连接");
                    showProgressDialog("等待接收体脂数据");
                    new Handler().postDelayed(() -> write(HexUtil.stringToAscii(commStr)), 1200);
                });
            }

            @Override
            public void onDisconnected() {
                isConnected = false;
                Log.e(TAG, "onDisconnected: ");
                cancelProgressDialog();
                runOnUiThread(() -> {
                    blueToothState.setText("蓝牙连接失败");
                });
            }
        });
    }

    private void queryData() {
        List<SBCL_DATA> fmList = NovaApplication.fdbmanger.findAllByWhere(SBCL_DATA.class,
                strWhere + " AND CL_TYPE = 'FM2' ORDER BY CL_TIME DESC");
        if (fmList != null && fmList.size() > 0) {
            try {
                fmModelHeight = GsonUtils.fromJson(fmList.get(0).getCL_VALUE(), FmModel.class);
                double height = Double.parseDouble(fmModelHeight.getHeight());
                double weight = Double.parseDouble(fmModelHeight.getWeight());
//                String bmi = String.format("%.2f", NovaGlobalConts.getBMI(height / 100.0, weight));
//                tv_height.setText(fmModelHeight.getHeight() + "cm");
//                tv_weight.setText(fmModelHeight.getWeight() + "kg");
//                tv_bmi.setText(bmi);

                // 处理体脂测量指令
                String weightStr = "";
                if (weight < 100) {
                    if (fmModelHeight.getWeight().length() < 3) {
                        weightStr = "0" + fmModelHeight.getWeight().replace(".", "") + "0";
                    } else {
                        weightStr = "0" + fmModelHeight.getWeight().replace(".", "");
                    }
                }
                String heightStr = "";
                if (fmModelHeight.getHeight().contains(".")) {
                    heightStr = fmModelHeight.getHeight().replace(".", "");
                } else {
                    heightStr = fmModelHeight.getHeight()+"0";
                }

                ARCHIVE_BASEINFO userinfo = NovaApplication.getUserInfo();
                // 0 女性； 1 男性
                String sex = "";
                if ("DM01-08_1".equals(userinfo.getSEX())) {
                    sex = "1";
                } else {
                    sex = "0";
                }
                LogUtils.file("性别: " + userinfo.getSEX() );
//                int age = IdCardUtil.IdNOToAge(userinfo.getIDCARD());
                int age = GlobalConts.getAge(userinfo.getBIRTHDAY());
                LogUtils.file("年龄: " + age );
                commStr = "#FM" + heightStr + weightStr + sex + age + "$";
                isHeightAndWeightDataExit = true;
                LogUtils.file("体脂测量指令: " + commStr );
                Log.e(TAG, "体脂测量指令: " + commStr );
            } catch (Exception e) {
                e.printStackTrace();
                isHeightAndWeightDataExit = false;
                tv_state.setText("身高体重数据不正确！");
                ToastUtils.showShort("身高体重数据不正确！");
            }
        } else {
            isHeightAndWeightDataExit = false;
            tv_state.setText("请先测量身高体重数据！");
            ToastUtils.showShort("请先测量身高体重数据！");
        }
    }

    private void connDevice() {
        if (isHeightAndWeightDataExit) {
            if (isConnected) {
                blueToothState.setText("蓝牙已连接");
                showProgressDialog("等待接收体脂数据");
                LogUtils.file("等待接收体脂数据: " + commStr );
                LogUtils.file("等待接收体脂数据Ascii: " + HexUtil.stringToAscii(commStr) );
                new Handler().postDelayed(() -> write(HexUtil.stringToAscii(commStr)), 1200);
            } else {
                showProgressDialog("正在连接设备");
                blueToothState.setText("蓝牙开始连接");
                Log.e(TAG, "startDevice: " + deviceEnum.getMac());
                mBleDevice.setConnect(true);
                mBleDevice.setMAC(deviceEnum.getMac());
                mBleDevice.connect(deviceEnum.getMac());
            }
        } else {
            ToastUtils.showShort("请先测量身高体重数据！");
        }
    }

    @Override
    public void startDevice() {
        connDevice();
        connDevice();
//        timer = new Timer();
//        task = new TimerTask() {
//            @Override
//            public void run() {
//                Message msg = new Message();
//                msg.what = 0;
//                handler.sendMessage(msg);
//            }
//        };
//        timer.schedule(task,6000);
    }

    @Override
    public void update(String hexStr) {
        //接收数据
        try {
            LogUtils.file("接收数据 " + hexStr );
            String ascii = hexToAscii(hexStr);
            LogUtils.file("接收数据ascii " + ascii );
            if (!commStr.equals(ascii)) {
                stringBuilderAscii.append(ascii);
            }
            if (stringBuilderAscii.toString().contains("$")) {
                LogUtils.file("接收数据ascii " + stringBuilderAscii.toString() );
                cancelProgressDialog();
                Log.e(TAG, "stringBuilderAscii: " + stringBuilderAscii.toString());
                saveData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 测量成功 保存数据
    private void saveData() {
        String data = stringBuilderAscii.toString();
        String d3 = data.substring(3, 4);
        String d4 = data.substring(4, 5);
//        ToastUtils.showShort("人体成分返回数据"+data);
//        new AlertDialog.Builder(DhCompositionActivity.this).setTitle("测试").setMessage("人体成分返回数据"+data)
//                .setPositiveButton("确定", null).show();
        if (d3.equals("E")) {
            // 测量失败
            if ("1".equals(d4)) {
                // 没有握好电极把手
            } else if ("2".equals(d4)) {
                // 测量姿势不正确
            } else if ("3".equals(d4)) {
                // 手过于干燥
            } else if ("4".equals(d4)) {
                // 脂肪率、BMI、基础代谢值超出正常范围
            } else if ("5".equals(d4)) {
                // 动作异常
            } else if ("6".equals(d4)) {
                // 动作异常
            } else if ("7".equals(d4)) {
                // 40秒内无人测量
            }
        } else if (d3.equals("C")) {
            // 测量成功
            if ("0".equals(d4)) {
                // 无人体成分数据
            } else {
                analysisData(data);
            }
        }
    }

    private void analysisData(String data) {
        String fp = String.valueOf(Double.parseDouble(data.substring(5, 8)) / 10.0);
        String fm = String.valueOf(Double.parseDouble(data.substring(8, 12)) / 10.0);
        String bmr = data.substring(12, 16);
        String tbwc = String.valueOf(Double.parseDouble(data.substring(16, 19)) / 10.0);
        String tbwcPc = String.valueOf(Double.parseDouble(data.substring(19, 21)));
        // 骨骼肌率
        double gljl = Double.parseDouble(data.substring(21, 24)) / 10.0;
        String gljlPc = data.substring(24, 26);
        // 内脏脂肪指数
        String vfal = String.valueOf(Double.parseDouble(data.substring(26, 29)) / 10.0);
        String vfalPc = String.valueOf(Double.parseDouble(data.substring(29, 31)));
        // 骨矿含量
        String gkhl = String.valueOf(Double.parseDouble(data.substring(31, 34)) / 10.0);
        String gkhlPc = String.valueOf(Double.parseDouble(data.substring(34, 36)));
        String ecf = String.valueOf(Double.parseDouble(data.substring(36, 39)) / 10.0);
        String icf = String.valueOf(Double.parseDouble(data.substring(39, 42)) / 10.0);
        String zsf = String.valueOf(Double.parseDouble(data.substring(42, 45)) / 10.0);
        String protein = String.valueOf(Double.parseDouble(data.substring(45, 48)) / 10.0);
        // 无机盐
        String wjy = String.valueOf(Double.parseDouble(data.substring(48, 51)) / 10.0);
        String bodyAge = data.substring(51, 53);
        String bodyScore = String.valueOf(Double.parseDouble(data.substring(53, 56)) / 10.0);

        double height = Double.parseDouble(fmModelHeight.getHeight());
        double weight = Double.parseDouble(fmModelHeight.getWeight());
        String bmi = String.format("%.2f", NovaGlobalConts.getBMI(height / 100.0, weight));
        String jirouliang = String.format("%.2f", (gljl * weight) / 100.0);
//        tv_height.setText(fmModelHeight.getHeight() + "cm");
//        tv_weight.setText(fmModelHeight.getWeight() + "kg");
//        tv_bmi.setText(bmi);
//        tv_zfl.setText(fm + "%");
//        tv_shuifen.setText(tbwc + "%");
//        tv_jirouliang.setText(jirouliang + "kg");
//        tv_guliang.setText(gkhl + "kg");
//        // 基础代谢
//        tv_jcdx.setText(bmr + "");
//        tv_nzzfdj.setText(vfal + "级");
//        tv_stnl.setText(bodyAge + "岁");
//        tv_dbzl.setText(protein + "%");
//        tv_xbwsl.setText(ecf + "%");

        FmModel fmModel = new FmModel();
        fmModel.setHeight(fmModelHeight.getHeight());
        fmModel.setWeight(fmModelHeight.getWeight());
        fmModel.setBmi(bmi);
        fmModel.setFm(fp);
        fmModel.setFp(fm);
        fmModel.setBmr(bmr);
        fmModel.setTbwc(tbwc);
        fmModel.setVfal(vfal);
        fmModel.setEcf(ecf);
        fmModel.setIcf(icf);
//        fmModel.setProtein(protein);
        fmModel.setBodyAge(bodyAge);
        fmModel.setBodyScore(bodyScore);
        fmModel.setMm(jirouliang);
        fmModel.setSm(gkhl);
        fmModel.setProteinRate(protein);
        fmModel.setEwr(ecf);

        tv_result.setText("测量结果：\n" + fmModel.toString());
        tv_state.setText("获取测量结果成功");

        DeviceShowSaveData.getDataShow(GsonUtils.toJson(fmModel), "RTCF_DH");
        DeviceShowSaveData.saveCop(GsonUtils.toJson(fmModel));

        System.out.println(fp);
        System.out.println(fm);
        System.out.println(bmr);
        System.out.println(tbwc);
        System.out.println(tbwcPc);
        System.out.println("tbwcPc:" + tbwcPc);
        System.out.println("gljl:" + gljl);
        System.out.println("vfal:" + vfal);
        System.out.println("vfalPc:" + vfalPc);
        System.out.println("gkhl:" + gkhl);
        System.out.println("gkhlPc:" + gkhlPc);
        System.out.println("ecf:" + ecf);
        System.out.println("icf:" + icf);
        System.out.println("zsf:" + zsf);
        System.out.println("protein:" + protein);
        System.out.println("wjy:" + wjy);
        System.out.println("bodyAge:" + bodyAge);
        System.out.println("bodyScore:" + bodyScore);
    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.e(TAG, "disconnectDevice: " );
        try {
            mBleDevice.setConnect(false);
            mBleDevice.disconnect();
            mBleDevice.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 16进制字符串转ascii码
     * @param hexStr
     * @return
     */
    public static String hexToAscii(String hexStr) {
        StringBuilder output = null;
        try {
            output = new StringBuilder("");
            for (int i = 0; i < hexStr.length(); i += 2) {
                String str = hexStr.substring(i, i + 2);
                output.append((char) Integer.parseInt(str, 16));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return output.toString();
    }

}
